<script setup>
import { ref, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getflow } from '@/api/statis'

const chartRef = ref(null)
let chart = null
const startDate = ref(null)
const endDate = ref(null)
const flowData = ref({})
const loading = ref(false)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return start
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return start
    }
  }
]

// 计算总流水
const totalAmount = computed(() => {
  return (
    Object.values(flowData.value).reduce((sum, curr) => sum + curr, 0) / 100
  )
})

// 计算日均流水
const averageAmount = computed(() => {
  const days = Object.keys(flowData.value).length
  return days ? totalAmount.value / days : 0
})

// 格式化金额
const formatMoney = (amount) => {
  return `¥${amount.toFixed(2)}`
}

// 获取流水数据
const fetchFlowData = async () => {
  try {
    const params = {
      startTime: startDate.value.toISOString(),
      endTime: endDate.value.toISOString()
    }

    const res = await getflow(params)
    if (res.code === 1) {
      flowData.value = res.data
      initChart()
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取流水数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 查询按钮点击事件
const handleQuery = async () => {
  if (!startDate.value || !endDate.value) {
    ElMessage.warning('请选择完整的日期范围')
    return
  }

  loading.value = true
  try {
    await fetchFlowData()
  } finally {
    loading.value = false
  }
}

// 日期变化处理
const handleStartDateChange = () => {
  // 只在选择开始日期时重置结束日期
  if (endDate.value && endDate.value < startDate.value) {
    endDate.value = null
  }
}

const handleEndDateChange = () => {
  // 结束日期变化时不做特殊处理
}

// 统计数据
const statistics = computed(() => [
  { label: '总流水', value: totalAmount.value },
  { label: '日均流水', value: averageAmount.value }
])

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  if (!chart) {
    chart = echarts.init(chartRef.value)
  }

  const chartData = Object.entries(flowData.value)
    .map(([date, amount]) => ({
      date,
      amount: amount / 100
    }))
    .sort((a, b) => new Date(a.date) - new Date(b.date))

  const option = {
    title: {
      text: '每日销售额',
      left: 'center',
      textStyle: {
        color: '#555',
        fontWeight: '600'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0]
        return `${data.name}<br/>金额: ¥${data.value.toFixed(2)}`
      }
    },
    xAxis: {
      type: 'category',
      data: chartData.map((item) => item.date),
      axisLabel: {
        rotate: 45,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => `¥${value}`,
        color: '#666'
      }
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        data: chartData.map((item) => item.amount),
        smooth: true,
        itemStyle: {
          color: '#66b1ff' // 修改线条颜色
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102,177,255,0.3)' }, // 修改面积颜色
            { offset: 1, color: 'rgba(102,177,255,0.1)' }
          ])
        }
      }
    ],
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '10%',
      containLabel: true
    }
  }

  chart.setOption(option)
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
  chart?.resize()
})

onMounted(() => {
  // 设置默认时间范围为最近7天
  endDate.value = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
  startDate.value = start

  // 初始加载数据
  handleQuery()
})
</script>

<template>
  <div class="flow-report">
    <el-card class="mb-4" shadow="always" style="border-radius: 8px">
      <template #header>
        <div class="card-header">
          <span class="report-title">销售流水统计</span>
          <div class="date-picker-group">
            <el-date-picker
              v-model="startDate"
              type="date"
              placeholder="开始日期"
              :shortcuts="dateShortcuts"
              prefix-icon="Calendar"
              @change="handleStartDateChange"
            />
            <span class="separator">至</span>
            <el-date-picker
              v-model="endDate"
              type="date"
              placeholder="结束日期"
              :disabled="!startDate"
              :min-date="startDate"
              prefix-icon="Calendar"
              @change="handleEndDateChange"
            />
            <el-button
              type="primary"
              @click="handleQuery"
              :loading="loading"
              style="margin-left: 0"
            >
              查询
            </el-button>
          </div>
        </div>
      </template>

      <!-- 流水总额统计卡片 -->
      <div class="statistics-cards">
        <el-card
          class="stat-card"
          shadow="hover"
          v-for="(stat, index) in statistics"
          :key="index"
        >
          <transition name="fade">
            <div class="stat-value" v-if="!loading">
              {{ formatMoney(stat.value) }}
            </div>
          </transition>
          <div class="stat-label">{{ stat.label }}</div>
        </el-card>
      </div>

      <!-- ECharts图表 -->
      <div ref="chartRef" class="chart-container"></div>
    </el-card>
  </div>
</template>

<style scoped>
.flow-report {
  padding: 20px;
  background-color: #f2f2f2; /* 浅色背景 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #555; /* 深灰色标题 */
}

.date-picker-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-picker-group .el-button {
  margin-left: 0px;
}

.separator {
  color: #606266;
}

.statistics-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  text-align: center;
  border-radius: 8px; /* 圆角卡片 */
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #66b1ff; /* 主题色 */
  margin-bottom: 8px;
}

.stat-label {
  color: #666;
}

.chart-container {
  height: 400px;
  width: 100%;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
